package org.example.nio;

import org.example.util.PathUtil;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class FileChannelExample {

    private PathUtil pathUtil = new PathUtil();

    /**
     * 底层使用零拷贝
     */
    @Test
    public void transferToAPITest(){
        // 获取文件的绝对路径
        String inputPath = pathUtil.getAbsolutePath("input.txt");
        String outputPath = pathUtil.getAbsolutePath("output.txt");
        try (FileInputStream fis = new FileInputStream(inputPath);
             FileOutputStream fos = new FileOutputStream(outputPath);
             FileChannel inputChannel = fis.getChannel();
             FileChannel outputChannel = fos.getChannel()) {
            // 参数：inputChannel的起始位置，传输数据的大小，目的channel
            // 返回值为传输的数据的字节数
            // transferTo一次只能传输2G的数据
            inputChannel.transferTo(0, inputChannel.size(), outputChannel);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
